const Sequelize = require('sequelize');

const POSTGRES_CONNECTION_STRING =
  process.env.POSTGRES_CONNECTION_STRING ||
  'postgres://postgres:password@localhost:6432/postgres';

async function addProjectDataset(projectDataset) {
  try {
    var sequelize = new Sequelize(POSTGRES_CONNECTION_STRING, {});
    var res = await sequelize.query(
      'select (select count(project_task_item.*) from project_task_item where project_task_item.dataset_id = :projectDatasetId ) as project_item,(select count(dataset_item.*) from dataset_item where dataset_item.dataset_id = :datasetId and is_folder = :isFolder) as dataset_item',
      {
        replacements: {
          datasetId: projectDataset.dataset_id,
          projectDatasetId: projectDataset.id,
          isFolder: false
        }
      }
    );
    const offset = res[0][0].project_item;
    const count = res[0][0].dataset_item;
    console.log(offset, count);
    if (parseInt(offset) < parseInt(count)) {
      //change state to async
      console.log('start sync');

      res = await sequelize.query(
        'UPDATE project_dataset SET state = :state WHERE id = :id',
        {
          replacements: {
            state: 'sync',
            id: projectDataset.id
          }
        }
      );

      console.log('update dataset state ok');

      res = await sequelize.query(
        'select id from dataset_item where dataset_item.dataset_id = :datasetId and is_folder = :isFolder ORDER BY id OFFSET :projectItems',
        {
          replacements: {
            projectItems: offset,
            datasetId: projectDataset.dataset_id,
            isFolder: false
          }
        }
      );

      console.log('select ids ok');

      for (let index = 0; index < res[0].length; index += 1) {
        const insertResult = await sequelize.query(
          'INSERT INTO project_task_item(project_id, item_id, dataset_id) values (:projectId, :itemId, :datasetId);',
          {
            replacements: {
              projectId: projectDataset.project_id,
              itemId: res[0][index].id,
              datasetId: projectDataset.id
            }
          }
        );
        console.log('update id: ', res[0][index].id);
      }

      //change state to async
      res = await sequelize.query(
        'UPDATE project_dataset SET state = :state WHERE id = :id',
        {
          replacements: {
            state: 'normal',
            id: projectDataset.id
          }
        }
      );
    }
    return res;
  } catch (e) {
    console.log(e);
    throw new Error(e);
  } finally {
    sequelize.close();
  }
}

module.exports.addProjectDataset = addProjectDataset;
